package com.fone.player.online.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astuetz.PagerSlidingTabStrip;
import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseFragment;
import com.fone.player.activity.search.SearchActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.LoginRst;
import com.fone.player.client.LoginRst.Mn;
import com.fone.player.client.Reporter;
import com.fone.player.client.Reporter.EventId;
import com.fone.player.client.Request;
import com.fone.player.client.Rst;
import com.fone.player.entity.CustomChannel;
import com.fone.player.entity.LabelInfo;
import com.fone.player.entity.LabelListlInfo;
import com.fone.player.entity.MnsetInfo;
import com.fone.player.online.activity.EveryoneWatchActivity;
import com.fone.player.online.adapter.ChannelAdapter;
import com.fone.player.online.adapter.OnlineAdapter;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.mobeta.android.dslv.DragSortListView;

/**
 * 在线视频页。
 */
public class OnlineFragment extends BaseFragment {
	/** 日志标签 */
	private static final String TAG = "OnlineFragment";

	private PagerSlidingTabStrip tabs;
	private ViewPager pager;
	private OnlineAdapter adapter;

	/** 标签页 */
	private List<LabelInfo> tabsList = new ArrayList<LabelInfo>();
	/** 自定义频道 */
	private List<LabelInfo> channelList = new ArrayList<LabelInfo>();

	private View mView;
	private DragSortListView dragList;
	private CheckBox moreCheckBox;
	private ChannelAdapter channelAdapter;

	private CheckBox hideCheckBox;
	private TextView titleText, tabsbg;
	private ImageView mCommonTopSearchIcon, mHotIcon;

	LabelInfo headInfo = new LabelInfo("", "全网热点", "100", "", "0", "1", "0");
	LabelInfo footInfo = new LabelInfo("", "软件推荐", "200", "", "0", "1", "0");

	public static OnlineFragment newInstance() {
		OnlineFragment f = new OnlineFragment();
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.fragment_online, container, false);
		}

		ViewGroup parent = (ViewGroup) mView.getParent();
		if (parent != null) {
			parent.removeView(mView);
		}
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		Log.i("onActivityCreated", "onActivityCreated login");
		Request.getInstance().login(2, new UpdateColumnCallback());
		initView();
	}

	private void initView() {
		// initData();
		initTabs(ApplicationManage.getAplicationManageInstance().labelList, StorageModule.getInstance().getCustomChannelList());
		initChannel();
		
		TextView tv = (TextView) mView.findViewById(R.id.appText);
		
		tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (hideCheckBox.isChecked()) {
					
					hideCheckBox.setChecked(false);
					tabs.setVisibility(View.VISIBLE);
					moreCheckBox.setVisibility(View.VISIBLE);
					
				} else {
					
					hideCheckBox.setChecked(true);
					tabs.setVisibility(View.GONE);
					moreCheckBox.setVisibility(View.GONE);
				}
				
			}
			
		});

		titleText = (TextView) mView.findViewById(R.id.titleText);
		
		titleText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (hideCheckBox.isChecked()) {
					
					hideCheckBox.setChecked(false);
					tabs.setVisibility(View.VISIBLE);
					moreCheckBox.setVisibility(View.VISIBLE);
					
				} else {
					
					hideCheckBox.setChecked(true);
					tabs.setVisibility(View.GONE);
					moreCheckBox.setVisibility(View.GONE);
				}
				
			}
			
		});
		
		hideCheckBox = (CheckBox) mView.findViewById(R.id.hideTab);
		mHotIcon = (ImageView) mView.findViewById(R.id.common_top_hot_icon_iv);
		mCommonTopSearchIcon = (ImageView) mView.findViewById(R.id.common_top_search_icon_iv);
		tabsbg = (TextView) mView.findViewById(R.id.tabs_bg);

		mCommonTopSearchIcon.setOnClickListener(new ClickListener());
		mHotIcon.setOnClickListener(new ClickListener());

		titleText.setText(tabsList.get(0).name);

		moreCheckBox = (CheckBox) mView.findViewById(R.id.moreCheckBox);

		tabs = (PagerSlidingTabStrip) mView.findViewById(R.id.tabs);
		pager = (ViewPager) mView.findViewById(R.id.pager);
		pager.setOffscreenPageLimit(2);
		// adapter = new
		// OnlineAdapter(getActivity().getSupportFragmentManager(),
		// channelList);
		adapter = new OnlineAdapter(getChildFragmentManager(), tabsList);

		pager.setAdapter(adapter);

		final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
		pager.setPageMargin(pageMargin);

		tabs.setTextColorResource(R.color.tab_unselect_color);
		tabs.setTextSelectedColorResource(R.color.tab_select_color);
		// 选中标签页底线
		tabs.setIndicatorColorResource(R.color.tab_select_color);
		tabs.setIndicatorHeight(3);
		// 标签页底线
		tabs.setUnderlineColorResource(R.color.tab_select_color);
		tabs.setUnderlineHeight(1);
		// 各标签间隔线
		tabs.setDividerColor(Color.TRANSPARENT);
		tabs.setViewPager(pager, titleText);

		tabs.setTextSize(ScreenUtil.dp2px(15));
		tabs.setTabPaddingLeftRight((ScreenUtil.getScreenWidthPix(getActivity()) - ScreenUtil.dp2px(15) * 14) / 8);
		tabs.setTypeface(null, 0);

		hideCheckBox.setOnCheckedChangeListener(new CheckListener());
		moreCheckBox.setOnCheckedChangeListener(new CheckListener());
	}

	/**
	 * 初始化频道列表数据
	 */
	private void initChannel() {
		dragList = (DragSortListView) mView.findViewById(R.id.more_list);
		channelAdapter = new ChannelAdapter(getActivity(), R.layout.item_more, R.id.title, channelList);

		dragList.setAdapter(channelAdapter);
		dragList.setDropListener(onDrop);
		dragList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		dragList.setOnItemClickListener(new DropItemCheckListener());

		// 初始化频道是否选中
		for (int i = 0; i < channelList.size(); i++) {

			if (channelList.get(i).isshow.equals("1")) {
				dragList.setItemChecked(i, true);
			} else {
				dragList.setItemChecked(i, false);
			}
		}
	}

	/**
	 * 标签页及自定义频道页初始化
	 */
	private void initTabs(LabelListlInfo labelList, List<CustomChannel> dbList) {

		List<LabelInfo> localList = new ArrayList<LabelInfo>();
		List<LabelInfo> serverList = new ArrayList<LabelInfo>();

		List<LabelInfo> cacheList = new ArrayList<LabelInfo>();

		channelList.clear();
		tabsList.clear();

		serverList.clear();
		cacheList.clear();

		/** 服务器返回数据成功. */
		if (labelList.getMnList() != null && labelList.getMnList().size() > 0) {

			L.v(TAG, "tab", "- online size() -" + labelList.getMnList().size());

			// 如果用户为登录状态
			if (UserInfoManager.isLogin()) {

				if (isDefault(labelList.getMnList())) {
					serverList.addAll(getServerList(labelList.getMnList()));
				} else {
					for (int i = 0; i < labelList.getMnList().size(); i++) {
						Mn mn = labelList.getMnList().get(i);

						LabelInfo info = new LabelInfo(mn.id, mn.name, mn.showtype, mn.url, mn.custom, mn.isshow, mn.isnew);
						serverList.add(info);
						L.v(TAG, "initTabs", info.toString());
					}
				}
			} else {
				L.v(TAG, "tab", "---------------serverList------------------");

				// 转换本地数据库栏目列表数据；
				if (dbList != null && !dbList.isEmpty()) {
					for (CustomChannel channel : dbList) {
						LabelInfo info = new LabelInfo(channel.getCustomChannelId(), channel.getCustomChannelName(), channel.getCustomChannelType(), channel.getCustomChannelUrl(), channel.getCustomChannelIsCustom() + "", channel.getCustomChannelIsShow() + "", channel.getCustomChannelIsNew() + "");
						localList.add(info);
						L.v(TAG, "initTabs", info.toString());
					}
					L.v(TAG, "tab", "-------------localList--------------------");

					// 将服务器返回数据全部设置为不显示
					for (Mn mn : labelList.getMnList()) {
						LabelInfo info = new LabelInfo(mn.id, mn.name, mn.showtype, mn.url, mn.custom, "0", mn.isnew);
						serverList.add(info);
					}

					// 排序顺序及是否显示以本地为准，对象的其他属性以服务器为准
					for (int i = 0; i < localList.size(); i++) {
						LabelInfo info = localList.get(i);
						for (LabelInfo labelInfo : serverList) {
							if (info.id.equals(labelInfo.id)) {
								LabelInfo newInfo = new LabelInfo(info.id, labelInfo.name, labelInfo.type, labelInfo.url, labelInfo.custom, info.isshow, labelInfo.isnew);
								channelList.add(newInfo);
								cacheList.add(labelInfo);
								break;
							}
						}
					}

					serverList.removeAll(cacheList);
				} else {
					serverList.addAll(getServerList(labelList.getMnList()));
				}

			}

			channelList.addAll(serverList);

			// 将channelList数据进行保存；
			List<CustomChannel> saveList = new ArrayList<CustomChannel>();

			// 取出要在标签页显示数据
			for (LabelInfo info : channelList) {
				// L.v(TAG, "initTabs", info.toString());

				// 将要显示的标签页数据取出
				if (info.isshow.equals("1")) {
					tabsList.add(info);
				}

				CustomChannel channel = new CustomChannel();
				channel.setCustomChannelIsCustom(info.custom);
				channel.setCustomChannelIsNew(info.isnew);
				channel.setCustomChannelIsShow(info.isshow);
				channel.setCustomChannelName(info.name);
				channel.setCustomChannelType(info.type);
				channel.setCustomChannelUrl(info.url);
				channel.setCustomChannelId(info.id);

				saveList.add(channel);
			}

			int i = StorageModule.getInstance().addCustomChannelList(saveList);

			L.v(TAG, "initTabs", "保存数据状态：" + i);

			channelList.add(0, headInfo);
			tabsList.add(footInfo);
			if (tabsList.size() > 9) {
				tabsList.subList(0, 8);
			}

			tabsList.add(0, headInfo);
		}

		/** 服务器返回数据失败. */
		else {
			// 本地有保存栏目列表数据
			if (dbList != null && !dbList.isEmpty()) {

				// 转换本地数据库栏目列表数据
				for (CustomChannel channel : dbList) {
					LabelInfo info = new LabelInfo(channel.getCustomChannelId(), channel.getCustomChannelName(), channel.getCustomChannelType(), channel.getCustomChannelUrl(), channel.getCustomChannelIsCustom() + "", channel.getCustomChannelIsShow() + "", channel.getCustomChannelIsNew() + "");
					localList.add(info);
				}
				channelList.addAll(localList);

				for (LabelInfo info : channelList) {
					L.v(TAG, "initTabs", info.toString());
					if (info.isshow.equals("1")) {
						tabsList.add(info);
					}
				}

				channelList.add(0, headInfo);

				tabsList.add(0, headInfo);
				tabsList.add(footInfo);

			}
			// 本地没有保存栏目列表数据
			else {
				// 标签页只显示"全网热点"和"软件推荐"
				tabsList.add(0, headInfo);
				tabsList.add(footInfo);

				// 自定义频道页只显示"全网热点"
				channelList.add(0, headInfo);
			}
		}
	}

	/**
	 * 不超过9个 服务器所有自定义项数据默认都是显示
	 */
	private List<LabelInfo> getServerList(List<Mn> mnList) {
		List<LabelInfo> serverList = new ArrayList<LabelInfo>(mnList.size());

		List<Integer> custom = new ArrayList<Integer>();
		for (int i = 0; i < mnList.size(); i++) {
			Mn mn = mnList.get(i);
			if (mn.custom.equals("0")) {
				custom.add(i);
			}
		}

		/** 当固定项大于9时 */
		if (custom.size() > 9) {
			for (int i = 0; i < mnList.size(); i++) {
				Mn mn = mnList.get(i);
				LabelInfo info = new LabelInfo(mn.id, mn.name, mn.showtype, mn.url, mn.custom, mn.isshow, mn.isnew);
				serverList.add(info);
			}
		} else {

			/** 计算得到自定义频道也要显示个数 */
			int showNum = 9 - custom.size();

			for (int i = 0; i < mnList.size(); i++) {
				Mn mn = mnList.get(i);

				if (mn.custom.equals("1")) {
					if (showNum > 0) {
						LabelInfo info = new LabelInfo(mn.id, mn.name, mn.showtype, mn.url, mn.custom, mn.isshow, mn.isnew);
						serverList.add(info);
						showNum--;
					} else {
						LabelInfo info = new LabelInfo(mn.id, mn.name, mn.showtype, mn.url, mn.custom, "0", mn.isnew);
						serverList.add(info);
					}
				} else {
					LabelInfo info = new LabelInfo(mn.id, mn.name, mn.showtype, mn.url, mn.custom, mn.isshow, mn.isnew);
					serverList.add(info);
				}
			}
		}

		return serverList;
	}

	/**
	 * 更新标签页 更改完成
	 */
	private void updataTabs() {

		List<LabelInfo> reChannelList = new ArrayList<LabelInfo>();
		List<LabelInfo> reTabsList = new ArrayList<LabelInfo>();

		// 拖动重排后，获取最新数据
		for (int i = 0; i < channelAdapter.getCount(); i++) {
			LabelInfo info = channelAdapter.getItem(i);

			// 判断是否是固定不可选择项
			if (info.custom.equals("0")) {
			} else {
				if (dragList.isItemChecked(i)) {
					info.isshow = "1";
				} else {
					info.isshow = "0";
				}
			}

			reChannelList.add(info);
		}

		L.v(TAG, "updataTabs", "reChannelList.size ：" + reChannelList.size());

		L.v(TAG, "updataTabs", "false");

		List<CustomChannel> saveList = new ArrayList<CustomChannel>();

		// 需将自定义栏目中的"全网热点"移除
		for (int i = 1; i < reChannelList.size(); i++) {
			LabelInfo info = reChannelList.get(i);
			L.v(TAG, "updataTabs", info.toString());

			// 将要显示的标签页数据取出
			if (info.isshow.equals("1")) {
				reTabsList.add(info);
			}

			CustomChannel channel = new CustomChannel();
			channel.setCustomChannelIsCustom(info.custom);
			channel.setCustomChannelIsNew(info.isnew);
			channel.setCustomChannelIsShow(info.isshow);
			channel.setCustomChannelName(info.name);
			channel.setCustomChannelType(info.type);
			channel.setCustomChannelUrl(info.url);
			channel.setCustomChannelId(info.id);

			saveList.add(channel);

		}

		// 如果用户为登录状态
		if (UserInfoManager.isLogin()) {

			// saveList
			List<MnsetInfo> mnsetList = new ArrayList<MnsetInfo>();
			int i = 0;
			for (CustomChannel customChannel : saveList) {
				MnsetInfo info = new MnsetInfo();
				info.setMnid(customChannel.getCustomChannelId());
				info.setShow(customChannel.getCustomChannelIsShow());
				info.setRank(i + "");
				mnsetList.add(info);
				i++;
			}
			// Gson gson = new Gson();
			// for (MnsetInfo mnsetInfo : mnsetList) {
			// L.v(TAG, "updataTabs", mnsetInfo.toString());
			// }
			// L.v(TAG, "updataTabs", gson.toJson(mnsetList));
			Request.getInstance().mnset(mnsetList, new ChannelCallBack());
		}

		// 将数据保存到SQLite
		int i = StorageModule.getInstance().addCustomChannelList(saveList);
		L.v(TAG, "updataTabs", "保存数据状态：" + i);

		reTabsList.add(0, headInfo);
		reTabsList.add(footInfo);

		// 刷新标签页，最好添加个数据比较，避免频繁刷新标签页
		adapter.initData(reTabsList);
		adapter.notifyDataSetChanged();
		tabs.setViewPager(pager);
		
		Log.i("updataTabs", "updataTabs login");
		
		Request.getInstance().login(2, new SetColumnCallback());

	}
	
	private class UpdateColumnCallback implements Callback<LoginRst> {

		@Override
		public void onSuccess(LoginRst t) {
			
			Log.i("UpdateColumnCallback", "UpdateColumnCallback destory" + destory);
			
			if (destory) {
				return;
			}

			Log.i("UpdateColumnCallback", "UpdateColumnCallback result" + t.result);

			if (t.result == 0) {
				
				//if (!ApplicationManage.getAplicationManageInstance().labelList.isEqual(t.mns.mnList)) {
					
					Log.i("UpdateColumnCallback", "UpdateColumnCallback isEqual");
				
					ApplicationManage.getAplicationManageInstance().labelList
						.setMnList(t.mns.mnList);
				
					initTabs(ApplicationManage.getAplicationManageInstance().labelList, StorageModule.getInstance().getCustomChannelList());
					
					adapter.initData(tabsList);
					adapter.notifyDataSetChanged();
					tabs.setViewPager(pager);
					
					initChannel();
					
				//}

			}

		}

		@Override
		public void onFailure(Error error) {
			
		}

	}

	
	private class SetColumnCallback implements Callback<LoginRst> {

		@Override
		public void onSuccess(LoginRst t) {
			
			Log.i("SetColumnCallback", "SetColumnCallback destory" + destory);
			

			if (t.result == 0) {
				
				ApplicationManage.getAplicationManageInstance().labelList
						.setMnList(t.mns.mnList);
				
				

			}

		}

		@Override
		public void onFailure(Error error) {
			
		}

	}

	/**
	 * 2014-06-20 产品和服务器认为当服务器返回默认显示数据超过9条时,当前数据则为默认数据,需要客户端进行在标签页显隐控制处理
	 */
	private boolean isDefault(List<Mn> mnList) {
		if (mnList.size() > 9) {
			int num = 0;
			for (Mn mn : mnList) {
				if (mn.custom.equals("0")) {
					num++;
					continue;
				} else if (mn.isshow.equals("1")) {
					num++;
					continue;
				}
			}

			if (num > 9) {
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	}

	private class ChannelCallBack implements Callback<Rst> {

		@Override
		public void onSuccess(Rst t) {
			if (destory) {
				return;
			}
			L.v(TAG, "updataTabs", "---------------onSuccess------------------" + t.result);
		}

		@Override
		public void onFailure(Error error) {
			if (destory) {
				return;
			}
			// TODO Auto-generated method stub
			L.v(TAG, "updataTabs", "---------------onFailure------------------");

		}

	}

	private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
		@Override
		public void drop(int from, int to) {
			L.v(TAG, "onDrop", "- from -" + from + "- to -" + to);
			if (from == 0 || to == 0) {
				showShortToast("全网热点不能拖动哦！");
				return;
			}
			if (from != to) {
				LabelInfo info = channelAdapter.getItem(from);
				channelAdapter.remove(info);
				channelAdapter.insert(info, to);
				dragList.moveCheckState(from, to);
			}
		}
	};

	private class DropItemCheckListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// TODO Auto-generated method stub
			L.v(TAG, "Drop", channelAdapter.getItem(position).name);
			
			if (dragList.isItemChecked(position)) {
				Reporter.logEditChannel(channelAdapter.getItem(position).id, 1, 0);
			}else {
				Reporter.logEditChannel(channelAdapter.getItem(position).id, 0, 1);
			}

			int showNum = 0;
			// 拖动重排后，获取最新数据
			for (int i = 0; i < channelAdapter.getCount(); i++) {
				LabelInfo info = channelAdapter.getItem(i);

				// 判断是否是固定不可选择项
				if (info.custom.equals("0")) {
					showNum++;
				} else {
					if (dragList.isItemChecked(i) && info.custom.equals("1")) {
						showNum++;
					}
				}
			}
//			if (showNum > 10) {
//				showShortToast("频道添加个数已达上限");
//				dragList.setItemChecked(position, false);
//			}
			L.v(TAG, "onItemClick", "-showNum-" + showNum);
		}

	}

	private class ClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.common_top_search_icon_iv:
				Reporter.logEvent(EventId.CLICK_SEARCH_BTN);
				startActivity(new Intent(getActivity(), SearchActivity.class));
				break;
			case R.id.common_top_hot_icon_iv:
				startActivity(new Intent(getActivity(), EveryoneWatchActivity.class));
				break;

			default:
				break;
			}

		}
	}

	private class CheckListener implements OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			switch (buttonView.getId()) {
			case R.id.hideTab:
				/* 标签页显隐 */
				//Reporter.logEvent(EventId.CLICK_TOTAL_BTN);
				if (isChecked) {
					tabs.setVisibility(View.GONE);
					moreCheckBox.setVisibility(View.GONE);
				} else {
					tabs.setVisibility(View.VISIBLE);
					moreCheckBox.setVisibility(View.VISIBLE);
				}
				break;

			case R.id.moreCheckBox:
				L.v(TAG, "CheckListener", "- isChecked -" + isChecked);
				if (isChecked) {
					Reporter.logEvent(EventId.CLICK_TOTAL_BTN);
					dragList.setVisibility(View.VISIBLE);
					tabsbg.setVisibility(View.VISIBLE);
					tabsbg.setText("配置您的自定义栏目");

				} else {
					dragList.setVisibility(View.GONE);
					tabsbg.setVisibility(View.GONE);
					updataTabs();
				}
				break;

			default:
				break;

			}
		}
	}

}
